package com.jumper.study.admin.bo;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.jumper.study.db.model.Account;
import com.jumper.study.db.model.Admin;
import com.jumper.study.db.model.Api;

public class AdminUserDetails implements UserDetails {
    private final Account account;

    private final Admin adminUser;

    private final List<Api> apiList;

    public AdminUserDetails(Account account, Admin adminUser, List<Api> apiList) {
        this.account = account;
        this.adminUser = adminUser;
        this.apiList = apiList;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (apiList == null) {
            return null;
        }
        List<SimpleGrantedAuthority> gaList = apiList.stream()
                .map(m -> new SimpleGrantedAuthority(m.getMethod() + ":" + m.getUri()))
                .collect(Collectors.toList());
        //所有用户都添加普通用户权限
        gaList.add(new SimpleGrantedAuthority("USER"));
        //todo test 添加admin权限
        if (adminUser != null && adminUser.isEnabled()) {
            gaList.add(new SimpleGrantedAuthority("ADMIN"));
        }
        return gaList;
    }

    @Override
    public String getPassword() {
        return account.getPassword();
    }

    @Override
    public String getUsername() {
        return account.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public Account getAccount() {
        return account;
    }

    public Admin getAdminUser() {
        return adminUser;
    }
}
